﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BilingualSentSearchEngine
{
    /// <summary>
    /// Summary description for TermTypeReader
    /// </summary>
    public class TermFormationReader
    {
        Dictionary<string, int> term2Offset = new Dictionary<string, int>();

        byte[] termData;
        MemoryStream ms;
        StreamReader sr;

        char[] sep = { '\t' };

        private Object thisLock = new Object();



        public TermFormationReader()
        {

        }

        public bool Open(string indexFileName, string dataFileName)
        {
            sr = new StreamReader(indexFileName);
            BinaryReader br = new BinaryReader(FileStream.Synchronized(sr.BaseStream));

            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                string term;
                int offset;

                term = br.ReadString();
                offset = br.ReadInt32();
                term2Offset.Add(term, offset);
            }

            br.Close();
            sr.Close();

            sr = new StreamReader(dataFileName);
            br = new BinaryReader(FileStream.Synchronized(sr.BaseStream));


            FileInfo fi = new FileInfo(dataFileName);
            termData = br.ReadBytes((int)(fi.Length));

            sr.Close();
            br.Close();

            ms = new MemoryStream(termData);
            sr = new StreamReader(MemoryStream.Synchronized(ms));

            return true;

        }

        public List<string> GetTermFormations(string term)
        {
            List<string> strList = new List<string>();

            if (term2Offset.ContainsKey(term) == true)
            {
                string[] arrayStr;
                lock (thisLock)
                {
                    sr.BaseStream.Seek(term2Offset[term], SeekOrigin.Begin);
                    sr.DiscardBufferedData();
                    arrayStr = sr.ReadLine().Split(sep);
                }

                foreach (string item in arrayStr)
                {
                    if (item != term)
                    {
                        strList.Add(item);
                    }
                }
            }

            return strList;

        }
    }
}
